package ink.lovejinhu.leetcode;

import ink.lovejinhu.common.ListNode;

/**
 * @author jinhu
 * created 2021-07-13 16:13
 */
public class Solution_0876 {
    /**
     * 链表中间的节点
     * 第一次未加头，代码写的不够优美
     *
     * @param head
     * @return
     */
    public ListNode middleNode(ListNode head) {
        if (head == null) return null;
        ListNode temp = new ListNode(Integer.MAX_VALUE);
        temp.next = head;
        ListNode slow = temp;
        ListNode fast = temp;
        ListNode preFast = null;

        while (fast != null) {
            preFast = fast.next;
            if (preFast == null) return slow.next;
            fast = fast.next.next;

            slow = slow.next;
        }
        return slow;
    }

    /**
     * 这个代码需要思考下
     *
     * @param head
     * @return
     */
    public ListNode middleNode1(ListNode head) {
        if (head == null) return null;

        ListNode slow = head;
        ListNode fast = head;
        ListNode preFast = null;

        while (slow != null && fast != null) {
            preFast = fast.next;
            if (preFast == null) return slow.next;
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}
